/* eslint-disable implicit-arrow-linebreak */
// Third Party
import { Icon } from '@iconify/react'
import { isObjEmpty } from '@utils'
import { FormikProvider, useFormik } from 'formik'
import React, { useEffect, useState } from 'react'
import { Check, Edit2, X } from 'react-feather'
import toast from 'react-hot-toast'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate, useParams } from 'react-router-dom'
import { Button, Card, CardBody, Form, Spinner } from 'reactstrap'

// Components
import { ToastContent } from '@src/components/toast'
import renderContent from '../../../../components/documents/helpers/helper'
import CustomSpinner from '../../../../components/spinner/Spinner'
import {
  getClientDocumentsAction,
  updateClientDocumentsAction
} from '../../../../redux/document/documentsAction'
import { resetGetDocumentById } from '../../../../redux/document/documentsSlice'

const clientDocumentPreview = () => {
  const params = useParams()
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const [edit, setEdit] = useState(false)
  const { id } = params

  const { getDocuments, getLoading, updateLoading } = useSelector(
    (state) => state.document
  )
  useEffect(() => {
    dispatch(getClientDocumentsAction({ id }))
    return () => {
      dispatch(resetGetDocumentById())
    }
  }, [])

  const formik = useFormik({
    initialValues: {
      content: getDocuments?.content || []
    },
    enableReinitialize: true,
    onSubmit: (values) => {
      if (isObjEmpty(formik.errors)) {
        const requiredAnswer = values.content.filter(
          (item) =>
            item.required === true && (item.type === 1 || item.type === 2)
        )

        const requiredRadio = values.content.filter(
          (item) => item.required === true && item.type === 4
        )

        const findEmptyAnswer = requiredAnswer.find(
          (item) =>
            item.answer === null ||
            item.answer === undefined ||
            item.answer === ''
        )
        const findEmptyRadio = requiredRadio.find(
          (item) =>
            item.radioCheck === null ||
            item.radioCheck === undefined ||
            item.radioCheck === ''
        )

        if (
          !isObjEmpty(findEmptyAnswer || {}) ||
          !isObjEmpty(findEmptyRadio || {})
        ) {
          toast((t) => (
            <ToastContent
              t={t}
              name="Please fill all the required fields"
              icon={<X size={14} />}
              color="danger"
            />
          ))
        } else {
          const data = {
            content: values.content
          }
          dispatch(
            updateClientDocumentsAction({
              data,
              id,
              callback: () => {
                setEdit(false)
              }
            })
          )
        }
      }
    }
  })
  return (
    <>
      <Card className="p-0">
        <div className="pt-3 p-2 bg-yellow page-header xSmall-up-between d-flex justify-content-between align-items-center">
          <div className="page-header--title d-f-center d-flex align-items-center w-100">
            <Icon
              className="page-header--title__leftArrow"
              icon="bx:chevron-left"
              width="40"
              height="40"
              onClick={() => {
                navigate(-1)
              }}
            />
            <span className="heading-1 t-gray">
              {getDocuments?.title || ''}
            </span>
          </div>
          {!edit && !getLoading && (
            <div className="client_profile--sub my-1">
              <Button
                type="button"
                size="sm"
                className="pd  edit-notes-bg-color whiteSpace"
                onClick={() => setEdit(true)}
              >
                <Edit2 size={12} />
                <span className="mx-1">Edit</span>
              </Button>
            </div>
          )}
        </div>

        <CardBody
          style={{ backgroundColor: 'white' }}
          className={getLoading && 'p-0'}
        >
          {getLoading ? (
            <CustomSpinner />
          ) : (
            <FormikProvider value={formik}>
              <Form onSubmit={formik.handleSubmit}>
                <div className="list_overview--appointments__description--soap__note skin-change">
                  {!!getDocuments &&
                    getDocuments?.content.map((content, i) => (
                      <div
                        key={i}
                        className="list_overview--appointments__description--soap__note--fragment"
                      >
                        <div className="list_overview--appointments__description--soap__note--heading">
                          <div className="DOT DOT--green me-1" />
                          <p className="d-flex align-items-center">
                            <strong>{content?.question}</strong>
                          </p>
                        </div>

                        {renderContent({
                          formik,
                          content,
                          contentIndex: i,
                          edit
                        })}
                      </div>
                    ))}
                </div>
                {/* Submit */}
                {edit && (
                  <div className="client_profile--sub my-1">
                    <Button
                      type="button"
                      size="sm"
                      className="button-cancel pd cancel-btn "
                      onClick={() => {
                        formik.handleReset()
                        setEdit(false)
                      }}
                    >
                      Cancel
                    </Button>

                    <Button
                      disabled={updateLoading || !formik.dirty}
                      type="submit"
                      size="sm"
                      className="button-success pd fw-bold"
                    >
                      {updateLoading ? (
                        <Spinner size="sm" />
                      ) : (
                        <Check size={14} strokeWidth={3} />
                      )}
                      <span className="pl-5px">Save</span>
                    </Button>
                  </div>
                )}
              </Form>
            </FormikProvider>
          )}
        </CardBody>
      </Card>
    </>
  )
}

export default clientDocumentPreview
